import sqlite3
import json
from typing import Dict, Any

class Database:
    def __init__(self, db_name: str = "questionnaire.db"):
        self.db_name = db_name
        self.conn = None
        self.cursor = None
        self.connect()
        self.create_tables()
    
    def connect(self):
        self.conn = sqlite3.connect(self.db_name)
        self.cursor = self.conn.cursor()
    
    def create_tables(self):
        self.cursor.execute('''
        CREATE TABLE IF NOT EXISTS questionnaires (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            user_id TEXT,
            dialog_id TEXT,
            message_id TEXT,
            message TEXT,
            user_tag_analysis TEXT,
            top_elements TEXT,
            questions TEXT,
            history TEXT,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )
        ''')
        self.conn.commit()
    
    def insert_questionnaire(self, data: Dict[str, Any]) -> bool:
        try:
            self.cursor.execute('''
            INSERT INTO questionnaires (
                user_id, dialog_id, message_id, message,
                user_tag_analysis, top_elements, questions, history
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
            ''', (
                data.get('userId'),
                data.get('dialogId'),
                data.get('messageId'),
                data.get('message'),
                data.get('userTagAnalysis'),
                data.get('topElements'),
                data.get('questions'),
                json.dumps(data.get('history', []), ensure_ascii=False)
            ))
            self.conn.commit()
            return True
        except Exception as e:
            print(f"Error inserting data: {e}")
            return False
    
    def get_all_questionnaires(self) -> list:
        self.cursor.execute('SELECT * FROM questionnaires')
        columns = [description[0] for description in self.cursor.description]
        results = []
        for row in self.cursor.fetchall():
            result = dict(zip(columns, row))
            try:
                result['history'] = json.loads(result['history'])
            except:
                result['history'] = []
            results.append(result)
        return results
    
    def close(self):
        if self.conn:
            self.conn.close()
    
    def delete_questionnaire(self, questionnaire_id: int) -> bool:
        try:
            self.cursor.execute('''
            DELETE FROM questionnaires WHERE id = ?
            ''', (questionnaire_id,))
            self.conn.commit()
            return True
        except Exception as e:
            print(f"Error deleting data: {e}")
            return False